/*
 * @Description: 标签
 * @Author: franktrue 807615827@qq.com
 * @Date: 2021-07-28 08:11:48
 * @LastEditTime: 2021-07-31 12:17:06
 */
package model

import (
	"gorm.io/gorm"
)

type Tag struct {
	*Model
	// 标签名称
	Name string `json:"name"`
	// 状态 0为禁用、1为启用
	State uint8 `json:"state"`
}

func (model Tag) TableName() string {
	return "blog_tag"
}

func (t Tag) Count(db *gorm.DB) (count int64, err error) {
	count = 0
	if t.Name != "" {
		db = db.Where("name = ?", t.Name)
	}
	err = db.Model(&t).Where("state = ?", t.State).Where("deleted_at = 0").Count(&count).Error
	return
}

func (t Tag) List(db *gorm.DB, pageOffset, pageSize int) (tags []*Tag, err error) {
	if pageOffset > 0 && pageSize > 0 {
		db = db.Offset(pageOffset).Limit(pageSize)
	}
	if t.Name != "" {
		db = db.Where("name = ?", t.Name)
	}
	db = db.Where("state = ?", t.State)
	if err = db.Model(&t).Where("deleted_at = 0").Find(&tags).Error; err != nil {
		return nil, err
	}
	return tags, nil
}

func (t Tag) Create(db *gorm.DB) error {
	return db.Create(&t).Error
}

func (t Tag) Update(db *gorm.DB, values interface{}) error {
	return db.Model(&t).Where("id = ? AND deleted_at = ?", t.ID, 0).Updates(values).Error
}

func (t Tag) Delete(db *gorm.DB) error {
	return db.Where("id = ? AND deleted_at = 0", t.ID).Delete(&t).Error
}
